<?php

namespace frontend\filters;


use Yii;
use common\models\db\User;

/**
 *
 */
class Access extends \common\filters\BaseFilter
{

    public function beforeAction($action)
    {
        if ($this->checkExcept()) {
            return true;
        }
        if (!Yii::$app->user->isGuest) {
            $this->owner->userId = Yii::$app->user->getId();
            return true;
        } else {
            $wxUser = Access::getWxUserCache();
            $user = isset($wxUser['openid']) && $wxUser['openid'] ? User::findByOpenid($wxUser['openid']) : null;
            if ($user) {
                Yii::$app->user->login($user, 3600 * 24 * 30);
                $this->owner->userId = $user->id;
                return true;
            }
            if (Yii::$app->getRequest()->isAjax) {
                $this->owner->error('未登录', 4002);
            } else {
                $request = Yii::$app->getRequest();
                $return = rawurlencode($request->hostInfo . $request->url);
                Yii::$app->controller->redirect('/site/login?return=' . $return);
                return false;
            }
        }
    }

    public static function getWxUserCache()
    {
        $data = Yii::$app->session->get('mobile_wx_user');
        if (!$data) {
            return null;
        }
        return $data;
    }

    public static function setWxUserCache($data)
    {
        Yii::$app->session->set('mobile_wx_user', $data);
    }

    public static function getOpenidCache()
    {
        $data = Yii::$app->session->get('mobile_wx_openid');
        if (!$data) {
            return '';
        }
        return $data;
    }

    public static function setOpenidCache($data)
    {
        Yii::$app->session->set('mobile_wx_openid', $data);
    }

    public static function getPid()
    {
        $data = Yii::$app->session->get('mobile_wx_pid');
        if (!$data) {
            return 1;
        }
        return $data;
    }

    public static function setPid($data)
    {
        Yii::$app->session->set('mobile_wx_pid', $data);
    }

    /**
     * @param $wxUser
     * @return User|null
     */
    public static function addUser($wxUser)
    {
        $user = isset($wxUser['openid']) && $wxUser['openid'] ? User::findByOpenid($wxUser['openid']) : null;
        if (!$user) {
            $user = new User();
            if ($wxUser) {
                $user->open_id = isset($wxUser['openid']) ? $wxUser['openid'] : '';
                $user->nick_name = isset($wxUser['nickname']) ? $wxUser['nickname'] : '';
                // gender 字段不存在，移除
                $user->avatar_url = isset($wxUser['headimgurl']) ? $wxUser['headimgurl'] : '';
            }
            $user->created_at = date('Y-m-d H:i:s');
            $user->updated_at = date('Y-m-d H:i:s');
            if (!$user->save()) {
                throw new  \RuntimeException($user->getFirstErrorMsg());
            }
        }
        return $user;
    }
}
